/**
 * 统一存储管理工具 - 兼容多种存储方式
 * 支持 localStorage、sessionStorage、uni-app存储、Vuex状态管理
 * 作者：仔仔
 * 日期：2025-11-08
 */

class StorageManager {
  constructor() {
    this.storageType = this.detectStorageType();
    this.prefix = 'zz_'; // 存储前缀，避免命名冲突
  }

  /**
   * 检测可用的存储类型
   */
  detectStorageType() {
    // 优先使用 uni-app 存储
    if (typeof uni !== 'undefined' && uni.setStorageSync) {
      return 'uni';
    }
    
    // 其次使用 localStorage
    if (typeof localStorage !== 'undefined') {
      return 'localStorage';
    }
    
    // 最后使用 sessionStorage
    if (typeof sessionStorage !== 'undefined') {
      return 'sessionStorage';
    }
    
    // 都不支持则使用内存存储
    return 'memory';
  }

  /**
   * 生成带前缀的键名
   */
  getKey(key) {
    return this.prefix + key;
  }

  /**
   * 设置存储项
   */
  set(key, value, options = {}) {
    const storageKey = this.getKey(key);
    const data = {
      value: value,
      timestamp: Date.now(),
      expire: options.expire || null, // 过期时间（毫秒）
      type: typeof value
    };

    try {
      switch (this.storageType) {
        case 'uni':
          uni.setStorageSync(storageKey, data);
          break;
        case 'localStorage':
          localStorage.setItem(storageKey, JSON.stringify(data));
          break;
        case 'sessionStorage':
          sessionStorage.setItem(storageKey, JSON.stringify(data));
          break;
        case 'memory':
          this.memoryStorage = this.memoryStorage || {};
          this.memoryStorage[storageKey] = data;
          break;
      }
      return true;
    } catch (error) {
      console.error('Storage set error:', error);
      return false;
    }
  }

  /**
   * 获取存储项
   */
  get(key, defaultValue = null) {
    const storageKey = this.getKey(key);
    let data = null;

    try {
      switch (this.storageType) {
        case 'uni':
          data = uni.getStorageSync(storageKey);
          break;
        case 'localStorage':
          const localData = localStorage.getItem(storageKey);
          data = localData ? JSON.parse(localData) : null;
          break;
        case 'sessionStorage':
          const sessionData = sessionStorage.getItem(storageKey);
          data = sessionData ? JSON.parse(sessionData) : null;
          break;
        case 'memory':
          data = this.memoryStorage ? this.memoryStorage[storageKey] : null;
          break;
      }

      // 检查数据是否存在且未过期
      if (data && data.value !== undefined) {
        // 检查是否过期
        if (data.expire && Date.now() - data.timestamp > data.expire) {
          this.remove(key); // 自动删除过期数据
          return defaultValue;
        }
        return data.value;
      }
      
      return defaultValue;
    } catch (error) {
      console.error('Storage get error:', error);
      return defaultValue;
    }
  }

  /**
   * 删除存储项
   */
  remove(key) {
    const storageKey = this.getKey(key);

    try {
      switch (this.storageType) {
        case 'uni':
          uni.removeStorageSync(storageKey);
          break;
        case 'localStorage':
          localStorage.removeItem(storageKey);
          break;
        case 'sessionStorage':
          sessionStorage.removeItem(storageKey);
          break;
        case 'memory':
          if (this.memoryStorage) {
            delete this.memoryStorage[storageKey];
          }
          break;
      }
      return true;
    } catch (error) {
      console.error('Storage remove error:', error);
      return false;
    }
  }

  /**
   * 清空所有存储（可指定前缀）
   */
  clear(prefix = this.prefix) {
    try {
      switch (this.storageType) {
        case 'uni':
          const uniKeys = uni.getStorageInfoSync().keys;
          uniKeys.forEach(key => {
            if (key.startsWith(prefix)) {
              uni.removeStorageSync(key);
            }
          });
          break;
        case 'localStorage':
          Object.keys(localStorage).forEach(key => {
            if (key.startsWith(prefix)) {
              localStorage.removeItem(key);
            }
          });
          break;
        case 'sessionStorage':
          Object.keys(sessionStorage).forEach(key => {
            if (key.startsWith(prefix)) {
              sessionStorage.removeItem(key);
            }
          });
          break;
        case 'memory':
          if (this.memoryStorage) {
            Object.keys(this.memoryStorage).forEach(key => {
              if (key.startsWith(prefix)) {
                delete this.memoryStorage[key];
              }
            });
          }
          break;
      }
      return true;
    } catch (error) {
      console.error('Storage clear error:', error);
      return false;
    }
  }

  /**
   * 检查存储项是否存在
   */
  has(key) {
    return this.get(key) !== null;
  }

  /**
   * 获取所有存储键名
   */
  keys() {
    const prefix = this.prefix;
    let allKeys = [];

    try {
      switch (this.storageType) {
        case 'uni':
          allKeys = uni.getStorageInfoSync().keys || [];
          break;
        case 'localStorage':
          allKeys = Object.keys(localStorage);
          break;
        case 'sessionStorage':
          allKeys = Object.keys(sessionStorage);
          break;
        case 'memory':
          allKeys = this.memoryStorage ? Object.keys(this.memoryStorage) : [];
          break;
      }

      // 过滤出带前缀的键名，并去除前缀
      return allKeys
        .filter(key => key.startsWith(prefix))
        .map(key => key.substring(prefix.length));
    } catch (error) {
      console.error('Storage keys error:', error);
      return [];
    }
  }

  /**
   * 获取存储信息
   */
  info() {
    const keys = this.keys();
    const info = {
      type: this.storageType,
      total: keys.length,
      keys: keys,
      size: 0
    };

    // 计算总大小（估算）
    keys.forEach(key => {
      const value = this.get(key);
      info.size += JSON.stringify(value).length;
    });

    return info;
  }

  /**
   * 设置存储项（异步版本）
   */
  async setAsync(key, value, options = {}) {
    return new Promise((resolve, reject) => {
      try {
        const result = this.set(key, value, options);
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 获取存储项（异步版本）
   */
  async getAsync(key, defaultValue = null) {
    return new Promise((resolve, reject) => {
      try {
        const result = this.get(key, defaultValue);
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 删除存储项（异步版本）
   */
  async removeAsync(key) {
    return new Promise((resolve, reject) => {
      try {
        const result = this.remove(key);
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }
}

// 创建单例实例
const storage = new StorageManager();

// 导出实例和类
const _storage = {
  // 基础方法
  set: (key, value, options) => storage.set(key, value, options),
  get: (key, defaultValue) => storage.get(key, defaultValue),
  remove: (key) => storage.remove(key),
  clear: (prefix) => storage.clear(prefix),
  has: (key) => storage.has(key),
  keys: () => storage.keys(),
  info: () => storage.info(),

  // 异步方法
  setAsync: (key, value, options) => storage.setAsync(key, value, options),
  getAsync: (key, defaultValue) => storage.getAsync(key, defaultValue),
  removeAsync: (key) => storage.removeAsync(key),


  // 存储类型检测
  getStorageType: () => storage.storageType
};

export default _storage;